﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Ranet.AgOlap.Controls.General;
using Galaktika.BI.Runtime.Services;
using Ranet.Olap.Core.Storage;
using Galaktika.BI.Silverlight.Commands;
using Galaktika.BI.Silverlight.Services;
using Ranet.Olap.Core;
using Ranet.ZipLib;

namespace Galaktika.BI.Silverlight.Controls.General
{
    public class StorageManagerEx : IStorageManager
    {
        UserControl Owner = null;
        public StorageManagerEx(UserControl owner)
            : base()
        {
            Owner = owner;
        }

        public IBindingContext Context { get; set; }

        void Raise_InvokeCompleted(DataLoaderEventArgs args)
        {
            EventHandler<DataLoaderEventArgs> handler = this.InvokeCompleted;
            if (handler != null)
            {
                if (Owner != null)
                {
                    Owner.Dispatcher.BeginInvoke(delegate { handler(this, args); });
                }
                else 
                {
                    handler(this, args); 
                }
            }
        }

        #region IStorageManager Members

        public event EventHandler<DataLoaderEventArgs> InvokeCompleted;

        public void Invoke(object schema, object state)
        {
            StorageActionArgs args = XmlUtility.XmlStr2Obj<StorageActionArgs>(schema.ToString());
            if (args != null)
            {
                IUserTaskManager taskManager = (IUserTaskManager)Context.Services.GetService(typeof(IUserTaskManager));
                if (taskManager != null)
                {
                    InvokeSchema invokeSchema = null;
                    String taskText = String.Empty;
                    invokeSchema = CommandBuilder.CreateStorageActionSchema((string)this.Context.UserData["_$Id"], args);

                    switch (args.ActionType)
                    {
                        case StorageActionTypes.Save:
                            taskText = Localization.AppTask_SavingToStorage;
                            break;
                        case StorageActionTypes.Load:
                            taskText = Localization.AppTask_LoadingFromStorage;
                            break;
                        case StorageActionTypes.GetList:
                            taskText = Localization.AppTask_GetObjectsListFromStorage;
                            break;
                    }
                    ChoiceControlInvokeSchemaWrapper wrapper = new ChoiceControlInvokeSchemaWrapper(invokeSchema, state);

                    taskManager.RunTaskAsync(
                        taskText,
                        param => this.InvokeCommand(param),
                        wrapper);
                }
            }
        }

        #endregion

        void InvokeCommand(object state)
        {
            ChoiceControlInvokeSchemaWrapper wrapper = state as ChoiceControlInvokeSchemaWrapper;
            if (wrapper != null)
            {
                InvokeSchema schema = wrapper.Schema;
                using (var cmd = CommandDispatcher.Dispatch(schema))
                {
                    InvokeResultSchema res = null;
                    try
                    {
                        res = cmd.Invoke();

                        String content = res.Content;
                        if (res.IsArchive)
                        {
                            content = ZipCompressor.DecompressFromBase64String(res.Content);
                        }

                        InvokeResultDescriptor result = new InvokeResultDescriptor(content);
                        if (res.ContentType == KnownContentTypes.Error)
                            result.ContentType = InvokeContentType.Error;

                        Raise_InvokeCompleted(new DataLoaderEventArgs(result, null, wrapper.UserState));
                    }
                    catch (ServerException ex)
                    {
                        InvokeResultDescriptor result = new InvokeResultDescriptor(ex.Message, InvokeContentType.Error);
                        Raise_InvokeCompleted(new DataLoaderEventArgs(result, ex, wrapper.UserState));
                    }
                }
            }
        }
    }
}
